<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="等级名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入等级名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
            <el-button
              type="primary"
              @click="openForm('create')"
              v-hasPermi="['brokerage:level:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="ID" align="center" prop="agentLevelId" min-width="80" />
      <el-table-column label="代理等级" align="left" prop="picUrl" min-width="110">
        <template #default="scope">
          <div class="flex">
            <el-image
              :preview-teleported="true"
              :src="scope.row.picUrl"
              class="w-[48px] h-[48px] m-r-10px rounded-4px align-middle"
            />
            <el-text>{{ scope.row.agentLevelName }}</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="权重" align="center" prop="agentLevel" min-width="110" />
      <el-table-column label="复购折扣" align="center" prop="discountPercent" min-width="110">
        <template #default="{ row }"> {{ row.discountPercent }}% </template>
      </el-table-column>
      <el-table-column label="代理数量" align="center" prop="agentNum" min-width="110" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        min-width="110"
      />
      <el-table-column label="操作" align="center" min-width="110px" fixed="right">
        <template #default="scope">
          <div class="flex items-center justify-center">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.agentLevelId)"
              v-hasPermi="['brokerage:level:update']"
            >
              编辑
            </el-button>

            <el-dropdown
              v-hasPermi="['trade:order:update']"
              @command="(command) => handleCommand(command, scope.row)"
            >
              <el-button link type="primary">
                <Icon icon="ep:d-arrow-right" />
                更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="reward"> 等级权益 </el-dropdown-item>
                  <el-dropdown-item command="promote"> 升级规则 </el-dropdown-item>
                  <el-dropdown-item v-if="checkPermi(['brokerage:level:delete'])" command="delete">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
      <template #empty>
        <Empty />
      </template>
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
    <!-- 设置等级奖励 -->
    <AgentLevelReward ref="AgentLevelRewardRef" @success="getList" />
    <!-- 设置晋升规则 -->
    <AgentLevelPromoteRule ref="AgentLevelPromoteRuleRef" @success="getList" />
  </ContentWrap>
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import * as LevelApi from '@/api/mall/trade/agent/level'
import AgentLevelReward from './components/AgentLevelReward.vue'
import AgentLevelPromoteRule from './components/AgentLevelPromoteRule.vue'
import { checkPermi } from '@/utils/permission'

const { push } = useRouter() // 路由跳转

/** 代理等级管理 **/
defineOptions({ name: 'AgentLevel' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数

const queryParams = reactive({
  name: null,
  status: null,
  pageNo: 1,
  pageSize: 10
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await LevelApi.getLevelList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleCommand = (command: string, row: any) => {
  switch (command) {
    case 'delete':
      handleDelete(row.agentLevelId)
      break
    case 'reward':
      setRecommendReward(row)
      break
    case 'promote':
      setRecommendPromoteRule(row)
      break
  }
}
/**
 * 设置升级规则
 */
const AgentLevelPromoteRuleRef = ref()
const setRecommendPromoteRule = (row: any) => {
  AgentLevelPromoteRuleRef.value.open(row, list.value)
}
/**
 * 设置推荐奖励
 */
const AgentLevelRewardRef = ref()
const setRecommendReward = (row: any) => {
  AgentLevelRewardRef.value.open(row, list.value)
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  if (type == 'update') {
    push({ name: 'AgentLevelEdit', params: { id } })
    return
  }
  push({ name: 'AgentLevelAdd' })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await LevelApi.deleteLevel(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getList()
})
onActivated(() => {
  getList()
})
</script>
